﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Common
{
    public class ExcelHelper<T>
    {
        /// <summary>
        /// 导出到内存流
        /// </summary>
        /// <param name="datas">需要导出的模型列表</param>
        /// <param name="fieldInfies">导出的字段列表信息</param>
        /// <param name="sheetRows">每个工作表的行数</param>
        /// <returns></returns>
        public static MemoryStream ToExcel(List<T> datas, List<ExportFieldInfo> fieldInfies, string ApiAddress, bool IsTitle = false, int sheetRows = 65536)
        {
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //需要生成工作溥总簿
            int sheetCount = datas.Count / sheetRows + 1;
            int rowCount = datas.Count;

            ICellStyle style = book.CreateCellStyle();
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
            style.Alignment = HorizontalAlignment.CenterSelection;//设置居中 方法2
            style.FillPattern = FillPattern.SolidForeground;

            ICellStyle style1 = book.CreateCellStyle();
            style1.Alignment = HorizontalAlignment.CenterSelection;//设置居中 方法2

            ICellStyle style2 = book.CreateCellStyle();
            IFont f = book.CreateFont();
            f.Boldweight = (short)FontBoldWeight.Bold;
            style2.SetFont(f);



            for (int i = 0; i < sheetCount; i++)
            {
                //添加一个sheet
                NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet" + Convert.ToString(i + 1));


                int rowTitleIndex = 0;

                if (IsTitle)
                {
                    //添加提示
                    //合并单元格
                    /**
                      第一个参数：从第几行开始合并
                      第二个参数：到第几行结束合并
                      第三个参数：从第几列开始合并
                      第四个参数：到第几列结束合并
                  **/
                    NPOI.SS.UserModel.IRow rowRemark1 = sheet.CreateRow(0);
                    ICell cell1 = rowRemark1.CreateCell(0);
                    cell1.SetCellValue("Disclaimer：");
                    cell1.CellStyle = style2;
                    NPOI.SS.UserModel.IRow rowRemark2 = sheet.CreateRow(1);
                    ICell cell2 = rowRemark2.CreateCell(0);
                    cell2.SetCellValue("The data acquired by is not suitable for usage in any medical diagnosis purpose.");
                    cell2.CellStyle = style2;
                    CellRangeAddress region1 = new CellRangeAddress(0, 0, 0, fieldInfies.Count - 1);
                    sheet.AddMergedRegion(region1);
                    CellRangeAddress region2 = new CellRangeAddress(1, 1, 0, fieldInfies.Count - 1);
                    sheet.AddMergedRegion(region2);
                    CellRangeAddress region3 = new CellRangeAddress(2, 2, 0, fieldInfies.Count - 1);
                    sheet.AddMergedRegion(region3);
                    rowTitleIndex = 3;
                }

                //给sheet添加第一行的头部标题
                NPOI.SS.UserModel.IRow rowTitle = sheet.CreateRow(rowTitleIndex);
                for (int k = 0; k < fieldInfies.Count; k++)
                {
                    sheet.SetColumnWidth(k, 300 * 20);
                    ICell cell = rowTitle.CreateCell(k);
                    cell.SetCellValue(fieldInfies.ElementAt(k).DisplayName);
                    cell.CellStyle = style;
                }
                if (datas != null && datas.Count > 0)
                {
                    //处理Excel一张工作簿只能放65536行记录的问题
                    //因为头部占一行，所以要减1
                    for (int j = 0; j < sheetRows - 1; j++)
                    {
                        //将数据逐步写入sheet各个行
                        NPOI.SS.UserModel.IRow rowtemp = sheet.CreateRow(j + 1 + rowTitleIndex);
                        int dataIndex = i * (sheetRows - 1) + j;
                        for (int k = 0; k < fieldInfies.Count; k++)
                        {
                            //获取类型
                            Type type = datas[dataIndex].GetType();
                            //获取指定名称的属性
                            System.Reflection.PropertyInfo propertyInfo = type.GetProperty(fieldInfies.ElementAt(k).FieldName);
                            //获取属性值
                            var value = propertyInfo.GetValue(datas[dataIndex], null);
                            switch (fieldInfies.ElementAt(k).DataType)
                            {
                                case DataTypeEnum.Int:
                                    rowtemp.CreateCell(k).SetCellValue(Convert.ToInt32(value));
                                    break;
                                case DataTypeEnum.Float:
                                    rowtemp.CreateCell(k).SetCellValue(Convert.ToDouble(value));
                                    break;
                                case DataTypeEnum.Double:
                                    rowtemp.CreateCell(k).SetCellValue(Convert.ToDouble(value));
                                    break;
                                case DataTypeEnum.String:
                                    ICell cell = rowtemp.CreateCell(k);
                                    cell.SetCellValue(Convert.ToString(value));
                                    cell.CellStyle = style1;
                                    // rowtemp.CreateCell(k).SetCellValue(Convert.ToString(value));
                                    break;
                                case DataTypeEnum.DateTime:
                                    rowtemp.CreateCell(k).SetCellValue(Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss.SSS"));
                                    break;
                                case DataTypeEnum.Date:
                                    rowtemp.CreateCell(k).SetCellValue(Convert.ToDateTime(value).ToString("yyyy-MM-dd"));
                                    break;
                                case DataTypeEnum.Img:
                                    if (value != null)
                                    {
                                        rowtemp.Height = 60 * 20;
                                        WebClient webClient = new WebClient();
                                        Byte[] bytes = webClient.DownloadData(ApiAddress + value.ToString());
                                        int pictureIdx = book.AddPicture(bytes, PictureType.JPEG);
                                        IDrawing patriarch = rowtemp.CreateCell(k).Sheet.CreateDrawingPatriarch();
                                        HSSFClientAnchor anchor = new HSSFClientAnchor(70, 10, 60, 14, k, j + 1 + rowTitleIndex, k + 1, j + 2 + rowTitleIndex);
                                        IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //所有记录循环完成
                        if (i * (sheetRows - 1) + (j + 1) == rowCount)
                        {
                            // 写入到客户端 
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            book.Write(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            return ms;
                        }
                    }
                }
                else
                {
                    // 写入到客户端 
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    book.Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }

            }
            return null;
        }


        /// <summary>
        /// Excel导入成DataTable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file, int Rowindex)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                // IRow header = sheet.GetRow(sheet.FirstRowNum);
                IRow header = sheet.GetRow(Rowindex);

                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                //for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                for (int i = Rowindex + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

    }

    public enum DataTypeEnum
    {
        Int = 0,
        Float = 1,
        Double = 2,
        String = 3,
        DateTime = 4,
        Date = 5,
        Img = 6
    }
    public class ExportFieldInfo
    {
        /// <summary>
        /// 字段名，用于反射获取值
        /// </summary>
        public string FieldName { get; set; }
        /// <summary>
        /// 中文名，用于导出标题
        /// </summary>
        public string DisplayName { get; set; }
        /// <summary>
        /// 数据类型，用于强制转换，并进行格式化,其实利用反射也可以获取到数据类型，此处因为要处理Date和Date的显示格式
        /// </summary>
        public DataTypeEnum DataType { get; set; }
    }
}
